import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import authService from '../../services/authService';

/**
 * 认证状态接口
 *
 * 管理用户登录状态、用户信息和认证令牌
 */
interface AuthState {
  /** 用户是否已认证 */
  isAuthenticated: boolean;
  /** 当前用户信息 */
  user: {
    id?: string;
    username?: string;
    role?: string;
  } | null;
  /** JWT访问令牌 */
  token: string | null;
  /** 加载状态 */
  loading: boolean;
  /** 错误信息 */
  error: string | null;
}

/**
 * 初始状态
 *
 * 从authService中获取已保存的认证状态
 */
const initialState: AuthState = {
  isAuthenticated: authService.isAuthenticated(),
  user: authService.getCurrentUser(),
  token: authService.getToken(),
  loading: false,
  error: null,
};

/**
 * 异步Action：用户登录
 *
 * 处理用户登录逻辑，包括认证和令牌获取
 */
export const loginAsync = createAsyncThunk(
  'auth/login',
  async (credentials: { username: string; password: string }) => {
    const response = await authService.login(credentials.username, credentials.password);
    return response;
  }
);

/**
 * 异步Action：用户登出
 *
 * 清除用户认证状态和本地存储
 */
export const logoutAsync = createAsyncThunk(
  'auth/logout',
  async () => {
    authService.logout();
  }
);

/**
 * 异步Action：验证令牌有效性
 *
 * 在应用启动时验证JWT令牌是否有效
 */
export const validateTokenAsync = createAsyncThunk(
  'auth/validateToken',
  async () => {
    const isValid = await authService.validateToken();
    if (!isValid) {
      authService.logout();
      throw new Error('Token invalid');
    }
    return authService.getCurrentUser();
  }
);

/**
 * 认证状态管理Slice
 *
 * 处理用户认证相关的状态管理和异步操作
 */
const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    /** 清除错误信息 */
    clearError: (state) => {
      state.error = null;
    },
    /** 设置用户信息 */
    setUser: (state, action: PayloadAction<AuthState['user']>) => {
      state.user = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      // 登录相关状态处理
      .addCase(loginAsync.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(loginAsync.fulfilled, (state, action) => {
        state.loading = false;
        state.isAuthenticated = true;
        state.user = action.payload.user;
        state.token = action.payload.token;
        state.error = null;
      })
      .addCase(loginAsync.rejected, (state, action) => {
        state.loading = false;
        state.isAuthenticated = false;
        state.user = null;
        state.token = null;
        state.error = action.error.message || '登录失败';
      })
      // 登出状态处理
      .addCase(logoutAsync.fulfilled, (state) => {
        state.isAuthenticated = false;
        state.user = null;
        state.token = null;
        state.error = null;
      })
      // 令牌验证状态处理
      .addCase(validateTokenAsync.fulfilled, (state, action) => {
        state.user = action.payload;
        state.isAuthenticated = true;
      })
      .addCase(validateTokenAsync.rejected, (state) => {
        state.isAuthenticated = false;
        state.user = null;
        state.token = null;
      });
  },
});

export const { clearError, setUser } = authSlice.actions;
export default authSlice.reducer;